import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Switch,
  Select,
  Tabs,
  Row,
  Col,
  Space,
  InputNumber,
  Tag,
  Typography,
  Tooltip,
  Statistic,
  Table,
  Popconfirm,
  Modal,
  Avatar,
  Descriptions,
  Divider,
} from 'antd';
import {
  SettingOutlined,
  SaveOutlined,
  ReloadOutlined,
  SafetyOutlined,
  GlobalOutlined,
  DatabaseOutlined,
  ApiOutlined,
  InfoCircleOutlined,
  CopyOutlined,
  FileProtectOutlined,
  DashboardOutlined,
  HddOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import {
  useSystemConfig,
  useSecurityConfig,
  usePermissionTemplates,
  usePermissionTemplateActions,
  useSystemStats,
  type SystemConfig,
  type SecurityConfig,
  type PermissionTemplate,
} from '@/hooks/common/useSettings';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;
const { Search } = Input;

const Settings: React.FC = () => {
  const [systemForm] = Form.useForm();
  const [securityForm] = Form.useForm();
  const [templateDetailVisible, setTemplateDetailVisible] = useState(false);
  const [viewingTemplate, setViewingTemplate] = useState<PermissionTemplate | null>(null);
  const [activeTab, setActiveTab] = useState('system');

  // 使用hooks
  const { config: systemConfig, loading: systemLoading, updateConfig: updateSystemConfig, resetConfig: resetSystemConfig } = useSystemConfig();
  const { config: securityConfig, loading: securityLoading, updateConfig: updateSecurityConfig, resetConfig: resetSecurityConfig } = useSecurityConfig();
  const { templates: permissionTemplates, loading: templatesLoading } = usePermissionTemplates();
  const { loading: templateActionLoading, createTemplate, updateTemplate, deleteTemplate, copyTemplate } = usePermissionTemplateActions();
  const { stats: systemStats, loading: statsLoading } = useSystemStats();

  // 初始化表单数据
  React.useEffect(() => {
    systemForm.setFieldsValue(systemConfig);
  }, [systemConfig, systemForm]);

  React.useEffect(() => {
    securityForm.setFieldsValue(securityConfig);
  }, [securityConfig, securityForm]);

  const handleSystemSubmit = async (values: SystemConfig) => {
    try {
      await updateSystemConfig(values);
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  const handleSecuritySubmit = async (values: SecurityConfig) => {
    try {
      await updateSecurityConfig(values);
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  const handleReset = () => {
    Modal.confirm({
      title: '确认重置',
      content: '确定要重置为默认配置吗？当前的设置将会丢失。',
      okText: '确定重置',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        if (activeTab === 'system') {
          resetSystemConfig();
          systemForm.resetFields();
        } else if (activeTab === 'security') {
          resetSecurityConfig();
          securityForm.resetFields();
        }
      },
    });
  };

  const handleViewTemplate = (template: PermissionTemplate) => {
    setViewingTemplate(template);
    setTemplateDetailVisible(true);
  };

  const handleEditTemplate = async (template: PermissionTemplate) => {
    try {
      await updateTemplate(template.id, template);
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  const handleCopyTemplate = async (template: PermissionTemplate) => {
    try {
      await copyTemplate(template.id);
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  const handleDeleteTemplate = async (id: string) => {
    try {
      await deleteTemplate(id);
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  const handleCreateTemplate = async () => {
    try {
      await createTemplate({
        name: '新权限模板',
        description: '新创建的权限模板',
        type: 'user',
        permissionCount: 0,
        usageCount: 0,
        permissions: [],
      });
    } catch (error) {
      // 错误已在hook中处理
    }
  };

  return (
    <div>
      <Card bodyStyle={{ padding: 0 }}>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Title level={4} style={{ margin: 0, color: '#262626' }}>
            <SettingOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            平台系统配置
          </Title>
          <Space>
            <Tooltip title="重置配置">
              <Button 
                icon={<ReloadOutlined />} 
                onClick={handleReset}
                style={{ borderRadius: 6 }}
              >
                重置配置
              </Button>
            </Tooltip>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              loading={activeTab === 'system' ? systemLoading : securityLoading}
              onClick={() => {
                if (activeTab === 'system') {
                  systemForm.submit();
                } else if (activeTab === 'security') {
                  securityForm.submit();
                }
              }}
              style={{ borderRadius: 6 }}
            >
              保存配置
            </Button>
          </Space>
        </div>

        <div>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={[
              {
                key: 'system',
                label: (
                  <span>
                    <SettingOutlined />
                    系统配置
                  </span>
                ),
                children: (
                  <Card style={{ borderRadius: 6 }} bodyStyle={{ padding: 0 }}>
                    <Form
                      form={systemForm}
                      layout="vertical"
                      onFinish={handleSystemSubmit}
                      style={{ padding: '24px' }}
                    >

                      {/* 运行状态 */}
                      <Card title="运行状态" size="small" style={{ marginBottom: 16 }}>
                        <Row gutter={24}>
                          <Col span={6}>
                            <Statistic
                              title="运行时间"
                              value={systemStats.uptime}
                              suffix="天"
                              prefix={<ClockCircleOutlined style={{ color: '#52c41a' }} />}
                              valueStyle={{ fontSize: '16px' }}
                            />
                          </Col>
                          <Col span={6}>
                            <Statistic
                              title="系统负载"
                              value={systemStats.systemLoad}
                              precision={1}
                              prefix={<DashboardOutlined style={{ color: '#1890ff' }} />}
                              valueStyle={{ fontSize: '16px' }}
                            />
                          </Col>
                          <Col span={6}>
                            <Statistic
                              title="内存使用"
                              value={systemStats.memoryUsage}
                              suffix="%"
                              prefix={<DatabaseOutlined style={{ color: '#faad14' }} />}
                              valueStyle={{ fontSize: '16px' }}
                            />
                          </Col>
                          <Col span={6}>
                            <Statistic
                              title="磁盘使用"
                              value={systemStats.diskUsage}
                              suffix="%"
                              prefix={<HddOutlined style={{ color: '#722ed1' }} />}
                              valueStyle={{ fontSize: '16px' }}
                            />
                          </Col>
                        </Row>
                        <Divider />
                        <Row gutter={24}>
                          <Col span={6}>
                            <Statistic
                              title="活跃租户"
                              value={systemStats.activeTenants}
                              prefix={<GlobalOutlined style={{ color: '#13c2c2' }} />}
                              valueStyle={{ fontSize: '16px' }}
                            />
                          </Col>
                          <Col span={6}>
                            <Statistic
                              title="总用户数"
                              value={systemStats.totalUsers}
                              prefix={<DatabaseOutlined style={{ color: '#eb2f96' }} />}
                              valueStyle={{ fontSize: '16px' }}
                            />
                          </Col>
                          <Col span={6}>
                            <Statistic
                              title="今日请求"
                              value={systemStats.todayRequests}
                              prefix={<ApiOutlined style={{ color: '#f5222d' }} />}
                              valueStyle={{ fontSize: '16px' }}
                            />
                          </Col>
                          <Col span={6}>
                            <Statistic
                              title="成功率"
                              value={systemStats.successRate}
                              suffix="%"
                              prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                              valueStyle={{ fontSize: '16px', color: '#52c41a' }}
                            />
                          </Col>
                        </Row>
                      </Card>

                      {/* 服务配置 */}
                      <Card title="服务配置" size="small" style={{ marginBottom: 16 }}>
                        <Row gutter={24}>
                          <Col span={12}>
                            <Form.Item
                              label="最大租户数量"
                              name="maxTenants"
                              rules={[{ required: true, message: '请输入最大租户数量' }]}
                            >
                              <InputNumber min={1} max={10000} style={{ width: '100%' }} />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item
                              label="默认存储配额(GB)"
                              name="defaultStorageQuota"
                              rules={[{ required: true, message: '请输入默认存储配额' }]}
                            >
                              <InputNumber min={1} max={1000} style={{ width: '100%' }} />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item
                              label="API限流(次/分钟)"
                              name="apiRateLimit"
                              rules={[{ required: true, message: '请输入API限流设置' }]}
                            >
                              <InputNumber min={10} max={100000} style={{ width: '100%' }} />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item
                              label="租户注册"
                              name="allowTenantRegistration"
                              valuePropName="checked"
                            >
                              <Space>
                                <Switch />
                                <Text type="secondary">允许新租户自主注册</Text>
                              </Space>
                            </Form.Item>
                          </Col>
                        </Row>
                      </Card>
                    </Form>
                  </Card>
                ),
              },
              {
                key: 'security',
                label: (
                  <span>
                    <SafetyOutlined />
                    安全策略
                  </span>
                ),
                children: (
                  <Card style={{ borderRadius: 6 }} bodyStyle={{ padding: 0 }}>
                    <div style={{ padding: '24px' }}>
                      <Form
                        form={securityForm}
                        layout="vertical"
                        onFinish={handleSecuritySubmit}
                      >
                        <Space direction="vertical" size={24} style={{ width: '100%' }}>
                          {/* 密码策略 */}
                          <Card title="密码策略" size="small">
                            <Row gutter={24}>
                              <Col span={8}>
                                <Form.Item
                                  label="最小长度"
                                  name="passwordMinLength"
                                  rules={[{ required: true, message: '请输入密码最小长度' }]}
                                >
                                  <InputNumber min={6} max={32} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="最大长度"
                                  name="passwordMaxLength"
                                  rules={[{ required: true, message: '请输入密码最大长度' }]}
                                >
                                  <InputNumber min={8} max={128} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="密码有效期(天)"
                                  name="passwordExpireDays"
                                  rules={[{ required: true, message: '请输入密码有效期' }]}
                                >
                                  <InputNumber min={0} max={365} style={{ width: '100%' }} placeholder="0表示永不过期" />
                                </Form.Item>
                              </Col>
                            </Row>
                            <Row gutter={24}>
                              <Col span={8}>
                                <Form.Item
                                  label="复杂度要求"
                                  name="requireComplexPassword"
                                  valuePropName="checked"
                                >
                                  <Space>
                                    <Switch />
                                    <Text type="secondary">必须包含大小写字母和数字</Text>
                                  </Space>
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="特殊字符"
                                  name="requireSpecialChars"
                                  valuePropName="checked"
                                >
                                  <Space>
                                    <Switch />
                                    <Text type="secondary">必须包含特殊字符</Text>
                                  </Space>
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="历史密码检查"
                                  name="passwordHistoryCheck"
                                  rules={[{ required: true, message: '请输入历史密码检查数量' }]}
                                >
                                  <InputNumber min={1} max={10} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                            </Row>
                            <div style={{ fontSize: '12px', color: '#666', marginTop: -16 }}>
                              不能与最近N次密码相同
                            </div>
                          </Card>

                          {/* 登录安全 */}
                          <Card title="登录安全" size="small">
                            <Row gutter={24}>
                              <Col span={8}>
                                <Form.Item
                                  label="最大尝试次数"
                                  name="maxLoginAttempts"
                                  rules={[{ required: true, message: '请输入最大尝试次数' }]}
                                >
                                  <InputNumber min={3} max={10} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="锁定时长(分钟)"
                                  name="lockoutDuration"
                                  rules={[{ required: true, message: '请输入锁定时长' }]}
                                >
                                  <InputNumber min={5} max={60} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="双因素认证"
                                  name="enableTwoFactor"
                                  valuePropName="checked"
                                >
                                  <Space>
                                    <Switch />
                                    <Text type="secondary">强制启用2FA</Text>
                                  </Space>
                                </Form.Item>
                              </Col>
                            </Row>
                            <Row gutter={24}>
                              <Col span={8}>
                                <Form.Item
                                  label="图形验证码"
                                  name="enableCaptcha"
                                  valuePropName="checked"
                                >
                                  <Space>
                                    <Switch />
                                    <Text type="secondary">登录时显示验证码</Text>
                                  </Space>
                                </Form.Item>
                              </Col>
                              <Col span={16}>
                                <Form.Item
                                  label="IP白名单"
                                  name="allowedIpRanges"
                                  help="每行一个IP地址，支持CIDR格式，留空表示不限制"
                                >
                                  <TextArea rows={3} placeholder="例如: 192.168.1.0/24" />
                                </Form.Item>
                              </Col>
                            </Row>
                          </Card>

                          {/* 会话管理 */}
                          <Card title="会话管理" size="small">
                            <Row gutter={24}>
                              <Col span={8}>
                                <Form.Item
                                  label="会话超时(分钟)"
                                  name="sessionTimeout"
                                  rules={[{ required: true, message: '请输入会话超时时间' }]}
                                >
                                  <InputNumber min={15} max={480} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="最大并发会话"
                                  name="maxConcurrentSessions"
                                  rules={[{ required: true, message: '请输入最大并发会话数' }]}
                                >
                                  <InputNumber min={1} max={10} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="空闲超时(分钟)"
                                  name="sessionIdleTimeout"
                                  rules={[{ required: true, message: '请输入空闲超时时间' }]}
                                >
                                  <InputNumber min={5} max={120} style={{ width: '100%' }} />
                                </Form.Item>
                              </Col>
                            </Row>
                            <Row gutter={24}>
                              <Col span={8}>
                                <Form.Item
                                  label="强制HTTPS"
                                  name="forceHttps"
                                  valuePropName="checked"
                                >
                                  <Space>
                                    <Switch />
                                    <Text type="secondary">仅允许HTTPS连接</Text>
                                  </Space>
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="会话保护"
                                  name="enableSessionProtection"
                                  valuePropName="checked"
                                >
                                  <Space>
                                    <Switch />
                                    <Text type="secondary">检测会话劫持</Text>
                                  </Space>
                                </Form.Item>
                              </Col>
                              <Col span={8}>
                                <Form.Item
                                  label="记住登录"
                                  name="allowRememberLogin"
                                  valuePropName="checked"
                                >
                                  <Space>
                                    <Switch />
                                    <Text type="secondary">允许记住登录状态</Text>
                                  </Space>
                                </Form.Item>
                              </Col>
                            </Row>
                          </Card>
                        </Space>
                      </Form>
                    </div>
                  </Card>
                ),
              },
              {
                key: 'templates',
                label: (
                  <span>
                    <FileProtectOutlined />
                    权限模板
                  </span>
                ),
                children: (
                  <Card style={{ borderRadius: 6 }} bodyStyle={{ padding: 0 }}>
                    <div style={{ padding: '24px' }}>
                      {/* 权限模板管理内容 */}
                      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Space>
                          <Search
                            placeholder="搜索权限模板"
                            allowClear
                            style={{ width: 300 }}
                          />
                          <Select defaultValue="all" style={{ width: 120 }}>
                            <Option value="all">全部类型</Option>
                            <Option value="admin">管理员</Option>
                            <Option value="user">普通用户</Option>
                            <Option value="readonly">只读用户</Option>
                          </Select>
                        </Space>
                        <Button 
                          type="primary" 
                          icon={<PlusOutlined />}
                          onClick={handleCreateTemplate}
                          style={{ borderRadius: 6 }}
                        >
                          新建模板
                        </Button>
                      </div>

                      <Table
                        dataSource={permissionTemplates}
                        pagination={{
                          pageSize: 10,
                          showSizeChanger: true,
                          showQuickJumper: true,
                          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                        }}
                        columns={[
                          {
                            title: '模板名称',
                            dataIndex: 'name',
                            key: 'name',
                            render: (text, record) => (
                              <Space>
                                <Avatar size={32} icon={<FileProtectOutlined />} style={{ backgroundColor: '#1890ff' }} />
                                <div>
                                  <div style={{ fontWeight: 'bold' }}>{text}</div>
                                  <Text type="secondary" style={{ fontSize: 12 }}>
                                    {record.description}
                                  </Text>
                                </div>
                              </Space>
                            ),
                          },
                          {
                            title: '类型',
                            dataIndex: 'type',
                            key: 'type',
                            width: 100,
                            render: (type) => (
                              <Tag color={type === 'admin' ? 'red' : type === 'user' ? 'blue' : 'green'}>
                                {type === 'admin' ? '管理员' : type === 'user' ? '普通用户' : '只读用户'}
                              </Tag>
                            ),
                          },
                          {
                            title: '权限数量',
                            dataIndex: 'permissionCount',
                            key: 'permissionCount',
                            width: 100,
                            render: (count) => (
                              <Text>{count} 个权限</Text>
                            ),
                          },
                          {
                            title: '使用次数',
                            dataIndex: 'usageCount',
                            key: 'usageCount',
                            width: 100,
                          },
                          {
                            title: '创建时间',
                            dataIndex: 'createTime',
                            key: 'createTime',
                            width: 120,
                            render: (time) => new Date(time).toLocaleDateString('zh-CN'),
                          },
                          {
                            title: '操作',
                            key: 'action',
                            width: 200,
                            render: (_, record) => (
                              <Space size="small">
                                <Tooltip title="查看详情">
                                  <Button
                                    type="text"
                                    size="small"
                                    icon={<EyeOutlined />}
                                    onClick={() => handleViewTemplate(record)}
                                  />
                                </Tooltip>
                                <Tooltip title="编辑">
                                  <Button
                                    type="text"
                                    size="small"
                                    icon={<EditOutlined />}
                                    onClick={() => handleEditTemplate(record)}
                                  />
                                </Tooltip>
                                <Tooltip title="复制">
                                  <Button
                                    type="text"
                                    size="small"
                                    icon={<CopyOutlined />}
                                    onClick={() => handleCopyTemplate(record)}
                                  />
                                </Tooltip>
                                <Popconfirm
                                  title="确定要删除这个权限模板吗？"
                                  description="删除后无法恢复，请谨慎操作"
                                  onConfirm={() => handleDeleteTemplate(record.id)}
                                  okText="确定"
                                  cancelText="取消"
                                >
                                  <Tooltip title="删除">
                                    <Button
                                      type="text"
                                      size="small"
                                      danger
                                      icon={<DeleteOutlined />}
                                    />
                                  </Tooltip>
                                </Popconfirm>
                              </Space>
                            ),
                          },
                        ]}
                        style={{ borderRadius: 6 }}
                      />
                    </div>
                  </Card>
                ),
              },
            ]}
          />
        </div>
      </Card>

      {/* 权限模板详情弹窗 */}
      <Modal
        title={
          <Space>
            <EyeOutlined style={{ color: '#1890ff' }} />
            <span>权限模板详情</span>
          </Space>
        }
        open={templateDetailVisible}
        onCancel={() => setTemplateDetailVisible(false)}
        footer={[
          <Button 
            key="edit" 
            type="primary" 
            onClick={() => {
              setTemplateDetailVisible(false);
              viewingTemplate && handleEditTemplate(viewingTemplate);
            }}
            style={{ borderRadius: 6 }}
          >
            编辑模板
          </Button>,
          <Button 
            key="close" 
            onClick={() => setTemplateDetailVisible(false)}
            style={{ borderRadius: 6 }}
          >
            关闭
          </Button>
        ]}
        width={800}
        style={{ borderRadius: 8 }}
      >
        {viewingTemplate && (
          <div>
            {/* 模板头部信息 */}
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Avatar 
                size={80} 
                icon={<FileProtectOutlined />} 
                style={{ backgroundColor: '#1890ff', marginBottom: 16 }}
              />
              <div>
                <Title level={3} style={{ margin: 0, color: '#262626' }}>
                  {viewingTemplate.name}
                </Title>
                <Text type="secondary" style={{ fontSize: 16 }}>
                  {viewingTemplate.description}
                </Text>
              </div>
              <div style={{ marginTop: 12 }}>
                <Tag color={viewingTemplate.type === 'admin' ? 'red' : viewingTemplate.type === 'user' ? 'blue' : 'green'}>
                  {viewingTemplate.type === 'admin' ? '管理员模板' : viewingTemplate.type === 'user' ? '普通用户模板' : '只读用户模板'}
                </Tag>
              </div>
            </div>

            <Divider />

            {/* 基本信息 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <InfoCircleOutlined style={{ marginRight: 8 }} />
              基本信息
            </Title>
            <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="模板名称">{viewingTemplate.name}</Descriptions.Item>
              <Descriptions.Item label="模板类型">
                <Tag color={viewingTemplate.type === 'admin' ? 'red' : viewingTemplate.type === 'user' ? 'blue' : 'green'}>
                  {viewingTemplate.type === 'admin' ? '管理员模板' : viewingTemplate.type === 'user' ? '普通用户模板' : '只读用户模板'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="权限数量">{viewingTemplate.permissionCount} 个</Descriptions.Item>
              <Descriptions.Item label="使用次数">{viewingTemplate.usageCount} 次</Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {new Date(viewingTemplate.createTime).toLocaleString('zh-CN')}
              </Descriptions.Item>
              <Descriptions.Item label="最后修改">
                {new Date(viewingTemplate.updateTime).toLocaleString('zh-CN')}
              </Descriptions.Item>
              <Descriptions.Item label="描述" span={2}>
                {viewingTemplate.description}
              </Descriptions.Item>
            </Descriptions>

            {/* 权限详情 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <SafetyOutlined style={{ marginRight: 8 }} />
              权限详情
            </Title>
            <div style={{ border: '1px solid #f0f0f0', borderRadius: 6, padding: 16, backgroundColor: '#fafafa' }}>
              <Row gutter={[8, 8]}>
                {viewingTemplate.permissions?.map((permission, index) => (
                  <Col key={index}>
                    <Tag color="blue" style={{ margin: 2 }}>
                      {permission}
                    </Tag>
                  </Col>
                ))}
              </Row>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Settings;